package com.fsai.cms.base;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;

/**
 * @author Jaffe<br>
 *         2014-8-4 == 下午02:21:29 Email: JaffeHe@gmail.com <br>
 * @version <br>
 * @ChangeLog <br>
 *            People Date Comment <br>
 */
public class CookieUtil {
	private final static String cookieDomainName = "user.cms.com";
	private final static String webKey = "pcdc-cms";
	private final static long cookieMaxAge = 60 * 60 * 24 * 30;//30天

	// 写入cookie
	public static void setCookie(String uname, String loginPwd, HttpServletResponse response) {
		long validTime = System.currentTimeMillis() + (cookieMaxAge * 1000);
		String cookieValueWithMd5 = getMD5(uname + ":" + loginPwd + ":" + validTime + ":" + webKey);

		String cookieValue = uname + ":" + validTime + ":" + cookieValueWithMd5;
		String cookieValueBase64 = new String(Base64.encodeBase64(cookieValue.getBytes()));
		Cookie cookie = new Cookie(cookieDomainName, cookieValueBase64);
		cookie.setMaxAge(60 * 60 * 24 * 30);
		cookie.setPath("/");
		response.addCookie(cookie);
	}

	// 读取cookie进行登录
	public static String readCookie(HttpServletRequest request, HttpServletResponse response)
			throws UnsupportedEncodingException {
		Cookie cookies[] = request.getCookies();
		String cookieValue = null;
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (cookieDomainName.equals(cookie.getName())) {
					cookieValue = cookie.getValue();
					break;
				}
			}
		}
		if (cookieValue == null) {
			return null;
		}
		String cookieValueAfterDecode = new String(Base64.decodeBase64(cookieValue), "utf-8");
		// 对解码后的值进行分拆,得到一个数组,如果数组长度不为3,就是非法登陆 
		String cookieValues[] = cookieValueAfterDecode.split(":");
		if (cookieValues.length != 3) {
			clearCookie(response);
			return null;
		}
		long validTimeInCookie = new Long(cookieValues[1]);
		if (validTimeInCookie < System.currentTimeMillis()) { // 删除Cookie 
			clearCookie(response);
			return null;
		}
		return cookieValueAfterDecode;
	}

	//比较cookie和数据库加密之后是否一致
	public static boolean checkCookieVal(String md5ValueInCookie, String username, String md5Pwd,
			long validTimeInCookie) {
		//		System.out.println("加密校驗字符串：" + username + "," + md5Pwd + "," + validTimeInCookie);
		String md5ValueFromUser = getMD5(username + ":" + md5Pwd + ":" + validTimeInCookie + ":" + webKey);
		// 将结果与Cookie中的MD5码相比较,如果相同,写入Session,自动登陆成功,并继续用户请求 
		if (md5ValueFromUser.equals(md5ValueInCookie)) {
			return true;
		}
		return false;
	}

	// 清除cookie
	public static void clearCookie(HttpServletResponse response) {
		Cookie cookie = new Cookie(cookieDomainName, null);
		cookie.setMaxAge(0);
		cookie.setPath("/");
		response.addCookie(cookie);
	}

	public static String getMD5(String value) {
		String result = null;
		try {
			byte[] valueByte = value.getBytes();
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(valueByte);
			result = toHex(md.digest());
		} catch (NoSuchAlgorithmException e1) {
			e1.printStackTrace();
		}
		return result;
	}

	private static String toHex(byte[] buffer) {
		StringBuffer sb = new StringBuffer(buffer.length * 2);
		for (int i = 0; i < buffer.length; i++) {
			sb.append(Character.forDigit((buffer[i] & 0xf0) >> 4, 16));
			sb.append(Character.forDigit(buffer[i] & 0x0f, 16));
		}
		return sb.toString();
	}

}
